#!groovy
def call(Map map){
def approvalMap = ['deployType': 'release']   
pipeline {
    environment {
        //git认证
        __ROPE_GIT_AUTH = "platform-git-auth"
        // hxgy认证
        SSH_AUTH = "ssh"
        // 部门
        DEPARTMENT = "${map.DEPARTMENT}"
        //应用名
        APPLICATION_NAME = "${map.APPLICATION_NAME}"
        // 开发环境部署地址
        DEPLOYMENT_ADDRESS_DEV = "${map.DEPLOYMENT_ADDRESS_DEV}"
        // 测试环境部署地址
        DEPLOYMENT_ADDRESS_TEST = "${map.DEPLOYMENT_ADDRESS_TEST}"
        // 预发布环境部署地址
        DEPLOYMENT_ADDRESS_RELEASE = "${map.DEPLOYMENT_ADDRESS_RELEASE}"
        // 生产环境部署地址
        DEPLOYMENT_ADDRESS_PRO = "${map.DEPLOYMENT_ADDRESS_PRO}"
        // git地址
        __ROPE_GIT_URL = "${map.GIT_URL}"
        // 机器人id
        __REBOOT = "${env.__REBOOT}"
        // web机器人
        __WEB_REBOOT = "${env.__WEB_REBOOT}"
    }
    agent {
        label 'web'
    }

    stages {
        stage('环境参数选择') {
            when {
                beforeAgent true
                branch 'master'
            }
            steps{
                script {
                    approvalMap = input (
                        message: '发布或者回滚项目?',
                        ok: '确定',
                        parameters: [
                            choice(choices: ['release', 'rollbak'], description: '部署类型（发布项目/回滚项目）', name: 'deployType')
                        ],
                        // 限制提交的用户id
                        submitter: 'hxgy,hxgy-platform-ops,hxgy-dm-business-ops,hxgy-im-business-ops,web-admin',
                        submitterParameter: 'approver'
                    )
                }
            }
        }
        
        stage('部署项目') {
            when {
                beforeAgent true
                equals expected: 'release', 
                actual: approvalMap['deployType'];
            }
            stages {
                stage('Git阶段') {
                    steps {
                        //sh 'printenv'
                        checkout([
                            $class: 'GitSCM',
                            branches: [[name: "${BRANCH_NAME}"]],
                            doGenerateSubmoduleConfigurations: false, 
                            extensions: [], 
                            submoduleCfg: [], 
                            userRemoteConfigs: [[credentialsId: "$__ROPE_GIT_AUTH",url: "${__ROPE_GIT_URL}"]]
                        ])
                    }
                }
                stage('build阶段'){ 
                    stages{
                        stage('修改yarn文件私服地址'){
                            steps{
                                // 修改yarn.lock中私服地址
                                sh "sed -i 's#https://npm.cd120.info#http://npm.cd120.info:8090#g' yarn.lock"
                            }
                        }
                        stage('安装依赖'){
                            steps{
                                sh "yarn"
                            }
                        }
                        stage('生产环境'){
                            when {
                                branch 'master'
                            }
                            steps {
                                sh "yarn build:prod" 
                            }
                        }
                        stage('预发布环境'){
                            when {
                                branch 'release*'
                            }
                            steps {
                                sh "yarn build:staging" 
                            }
                        }
                        stage('测试环境'){
                            when {
                                branch 'develop'
                            }
                            steps {
                                sh "yarn build:dev" 
                            }
                        }
                        stage('开发环境'){
                            when {
                                branch 'feature*'
                            }
                            steps {
                                sh "yarn build:dev" 
                            }
                        }
                    }
                }
                stage('config阶段'){
                    stages{
                        // 配置-hosts
                        //生产环境
                        stage('生产环境'){
                            when {
                                branch 'master'
                            }
                            steps {
                                withCredentials([usernamePassword(credentialsId: "${SSH_AUTH}", passwordVariable: 'password', usernameVariable: 'username')]) {
                                    script {
                                        __DEPLOY_ENV = "生产环境"
                                        DEPLOYMENT = "${DEPLOYMENT_ADDRESS_PRO}"
                                        writeFile file: 'hosts', text: """[hxgy]
${DEPLOYMENT_ADDRESS_PRO}
[all:vars]
ansible_ssh_user=${username}
ansible_ssh_pass=${password}"""
                                    }
                                }
                            }
                        }
                        //预发布环境
                        stage('预发布环境'){
                            when {
                                branch 'release*'
                            }
                            steps {
                                withCredentials([usernamePassword(credentialsId: "${SSH_AUTH}", passwordVariable: 'password', usernameVariable: 'username')]) {
                                    script {
                                        __DEPLOY_ENV = "预发布环境"
                                        DEPLOYMENT = "${DEPLOYMENT_ADDRESS_RELEASE}"
                                        writeFile file: 'hosts', text: """[hxgy]
${DEPLOYMENT_ADDRESS_RELEASE}
[all:vars]
ansible_ssh_user=${username}
ansible_ssh_pass=${password}"""
                                    }

                                }
                            }
                        }
                        // 测试环境
                        stage('测试环境'){
                            when {
                                branch 'develop'
                            }
                            steps {
                                withCredentials([usernamePassword(credentialsId: "${SSH_AUTH}", passwordVariable: 'password', usernameVariable: 'username')]) {
                                    script{
                                        __DEPLOY_ENV = "测试环境"
                                        DEPLOYMENT = "${DEPLOYMENT_ADDRESS_TEST}"
                                        writeFile file: 'hosts', text: """[hxgy]
${DEPLOYMENT_ADDRESS_TEST}
[all:vars]
ansible_ssh_user=${username}
ansible_ssh_pass=${password}"""
                                    }

                                }
                            }
                        }
                        // 开发环境
                        stage('开发环境'){
                            when {
                                branch 'feature*'
                            }
                            steps {
                                withCredentials([usernamePassword(credentialsId: "${SSH_AUTH}", passwordVariable: 'password', usernameVariable: 'username')]) {
                                    script{
                                        __DEPLOY_ENV = "开发环境"
                                        DEPLOYMENT = "${DEPLOYMENT_ADDRESS_DEV}"
                                        writeFile file: 'hosts', text: """[hxgy]
${DEPLOYMENT_ADDRESS_DEV}
[all:vars]
ansible_ssh_user=${username}
ansible_ssh_pass=${password}"""
                                    }
                                }
                            }
                        }
                        // 配置 - nginx、playbook
                        stage('config'){
                            steps{
                                // nginx配置
                                writeFile file: "${APPLICATION_NAME}.conf", text: """
location /${APPLICATION_NAME} {
	root /data/hxgy/workspace/deploy/web;
    try_files \$uri \$uri/ /${APPLICATION_NAME}/index.html;
    allow all;
    add_header pragma no-cache;
    add_header cache-control no-cache;
    add_header expires 0;
}                     
"""
                                //剧本
                                writeFile file: 'playbook.yml', text: """- hosts: hxgy
  remote_user: hxgy
  tasks:
    - name: create-1
      file: path=workspace/deploy/web/${APPLICATION_NAME} state=directory
    - name: backup-2
      file: path=workspace/deploy/backup/${APPLICATION_NAME} state=directory
    - name: copy-backup-3
      ignore_errors: yes
      command: cp -rf . ../../backup/${APPLICATION_NAME}
      args:
          chdir: "workspace/deploy/web/${APPLICATION_NAME}/"
    - name: copy-new-4
      copy:
        src: "{{ item }}"
        dest: "workspace/deploy/web/${APPLICATION_NAME}/"
      with_items:
        - dist
    - name: copy local
      shell: cp -rf dist/* . && rm -rf dist
      args:
          chdir: "workspace/deploy/web/${APPLICATION_NAME}/"
    - name: copy nginx
      copy:
        src: "{{ item }}"
        dest: "workspace/server/nginx-1.16.1/conf/web.d/"
      with_items:
        - ${APPLICATION_NAME}.conf
"""    
                            }
                        }
                    }
                }
                stage('Ansible部署阶段'){
                    steps{
                        // 执行
                        ansiblePlaybook disableHostKeyChecking: true, installation: 'ansible', inventory: 'hosts', playbook: 'playbook.yml'
                    }
                }
            }
            post {
                //  钉钉发布成功通知
                success {
                    echo '构建成功'
                    wrap([$class: 'BuildUser']) {
                        //sh 'printenv'
                        dingtalk (
                            robot: "${__REBOOT}",
                            type: 'ACTION_CARD',
                            title: "你有新的发布消息，请注意查收",
                            text: [
                                "# WEB项目名称-${APPLICATION_NAME}",
                                "-----------------------",
                                "* 任务: #${BUILD_NUMBER}  ",
                                "* 部署状态: 成功 ",
                                "* 执行人: ${BUILD_USER_ID}  ",
                                "* 执行人描述: ${BUILD_USER}  ",
                                "* 部署环境: ${__DEPLOY_ENV}  ",
                                "* 部署主机: ${DEPLOYMENT}  ",
                                "* 部署路径: workspace/deploy/web/${APPLICATION_NAME}  ",
                                "-----------------------"
                                
                            ],
                            btns: [
                                [
                                    title: 'jenkins详情',
                                    actionUrl: "${BUILD_URL}"
                                ]
                            ],
                            btnLayout: 'V'
                        )
                    }

                    wrap([$class: 'BuildUser']) {
                        //sh 'printenv'
                        dingtalk (
                            robot: "${__WEB_REBOOT}",
                            type: 'ACTION_CARD',
                            title: "你有新的发布消息，请注意查收",
                            text: [
                                "# WEB项目名称-${APPLICATION_NAME}",
                                "-----------------------",
                                "* 任务: #${BUILD_NUMBER}  ",
                                "* 部署状态: 成功 ",
                                "* 执行人: ${BUILD_USER_ID}  ",
                                "* 执行人描述: ${BUILD_USER}  ",
                                "* 部署环境: ${__DEPLOY_ENV}  ",
                                "* 部署主机: ${DEPLOYMENT}  ",
                                "* 部署路径: workspace/deploy/web/${APPLICATION_NAME}  ",
                                "-----------------------"
                                
                            ],
                            btns: [
                                [
                                    title: 'jenkins详情',
                                    actionUrl: "${BUILD_URL}"
                                ]
                            ],
                            btnLayout: 'V'
                        )
                    }   
                }
            }
        }
        stage('回滚项目') {
            when {
                beforeAgent true
                equals expected: 'rollbak', 
                actual: approvalMap['deployType'];
            }
            stages {
                stage("回滚项目"){
                    stages {
                        // 配置playbook
                        stage('config'){
                            steps{
                                writeFile file: 'playbook.yml', text: """- hosts: hxgy
  remote_user: hxgy
  tasks:
    - name: copy-local-2
      ignore_errors: yes
      command: cp -R ../../backup/${APPLICATION_NAME}/* .
      args:
          chdir: "workspace/deploy/web/${APPLICATION_NAME}/"

"""
                            }
                        }
                        // 配置-hosts
                        //生产环境
                        stage('生产环境'){
                            when {
                                branch 'master'
                            }
                            steps {
                                withCredentials([usernamePassword(credentialsId: "${SSH_AUTH}", passwordVariable: 'password', usernameVariable: 'username')]) {
                                    script{
                                        __DEPLOY_ENV = "生产环境"
                                        DEPLOYMENT = "${DEPLOYMENT_ADDRESS_PRO}"
                                        writeFile file: 'hosts', text: """[hxgy]
${DEPLOYMENT_ADDRESS_PRO}
[all:vars]
ansible_ssh_user=${username}
ansible_ssh_pass=${password}"""
                                    }
                                }
                            }
                        }
                        //预发布环境
                        stage('预发布环境'){
                            when {
                                branch 'release*'
                            }
                            steps {
                                withCredentials([usernamePassword(credentialsId: "${SSH_AUTH}", passwordVariable: 'password', usernameVariable: 'username')]) {
                                    script{
                                        __DEPLOY_ENV = "预发布环境"
                                        DEPLOYMENT = "${DEPLOYMENT_ADDRESS_RELEASE}"
                                        writeFile file: 'hosts', text: """[hxgy]
${DEPLOYMENT_ADDRESS_RELEASE}
[all:vars]
ansible_ssh_user=${username}
ansible_ssh_pass=${password}"""
                                    }
                                }
                            }
                        }
                        // 测试环境
                        stage('测试环境'){
                            when {
                                branch 'develop'
                            }
                            steps {
                                withCredentials([usernamePassword(credentialsId: "${SSH_AUTH}", passwordVariable: 'password', usernameVariable: 'username')]) {
                                    script{
                                        __DEPLOY_ENV = "测试环境"
                                        DEPLOYMENT = "${DEPLOYMENT_ADDRESS_TEST}"
                                        writeFile file: 'hosts', text: """[hxgy]
${DEPLOYMENT_ADDRESS_TEST}
[all:vars]
ansible_ssh_user=${username}
ansible_ssh_pass=${password}"""
                                    }
                                }
                            }
                        }
                        // 开发环境
                        stage('开发环境'){
                            when {
                                branch 'feature*'
                            }
                            steps {
                                withCredentials([usernamePassword(credentialsId: "${SSH_AUTH}", passwordVariable: 'password', usernameVariable: 'username')]) {
                                    script{
                                        __DEPLOY_ENV = "开发环境"
                                        DEPLOYMENT = "${DEPLOYMENT_ADDRESS_DEV}"
                                        writeFile file: 'hosts', text: """[hxgy]
${DEPLOYMENT_ADDRESS_DEV}
[all:vars]
ansible_ssh_user=${username}
ansible_ssh_pass=${password}"""
                                    }
                                }
                            }
                        }
                        //执行ansiblePlaybook
                        stage('执行ansible'){
                            steps{
                                ansiblePlaybook disableHostKeyChecking: true, installation: 'ansible', inventory: 'hosts', playbook: 'playbook.yml'
                            }
                        }

                    }
                }
            }
            post {
            //  钉钉回滚成功通知
                success {
                    echo '回滚成功'
                    wrap([$class: 'BuildUser']) {
                        dingtalk (
                            robot: "${__REBOOT}",
                            type: 'ACTION_CARD',
                            title: "你有新的回滚消息，请注意查收",
                            text: [
                                "# WEB项目名称-${APPLICATION_NAME}",
                                "-----------------------",
                                "* 任务: #${BUILD_NUMBER}  ",
                                "* 部署状态: 成功 ",
                                "* 执行类型: 项目回滚  ",
                                "* 执行人: ${BUILD_USER_ID}  ",
                                "* 执行人描述: ${BUILD_USER}  ",
                                "* 部署环境: ${__DEPLOY_ENV}  ",
                                "* 部署主机: ${DEPLOYMENT}  ",
                                "* 部署路径: workspace/deploy/web/${APPLICATION_NAME}  ",
                                "-----------------------"
                                
                            ],
                            btns: [
                                [
                                    title: 'jenkins详情',
                                    actionUrl: "${BUILD_URL}"
                                ]
                            ],
                            btnLayout: 'V'
                        )
                    }
                    wrap([$class: 'BuildUser']) {
                        dingtalk (
                            robot: "${__WEB_REBOOT}",
                            type: 'ACTION_CARD',
                            title: "你有新的回滚消息，请注意查收",
                            text: [
                                "# WEB项目名称-${APPLICATION_NAME}",
                                "-----------------------",
                                "* 任务: #${BUILD_NUMBER}  ",
                                "* 部署状态: 成功 ",
                                "* 执行类型: 项目回滚  ",
                                "* 执行人: ${BUILD_USER_ID}  ",
                                "* 执行人描述: ${BUILD_USER}  ",
                                "* 部署环境: ${__DEPLOY_ENV}  ",
                                "* 部署主机: ${DEPLOYMENT}  ",
                                "* 部署路径: workspace/deploy/web/${APPLICATION_NAME}  ",
                                "-----------------------"
                                
                            ],
                            btns: [
                                [
                                    title: 'jenkins详情',
                                    actionUrl: "${BUILD_URL}"
                                ]
                            ],
                            btnLayout: 'V'
                        )
                    }   
                }
            }
        }
    }
    post{
        //清理空间-生成环境不清空空间
        //always {
        //    echo '构建后清理工作空间'
        //    deleteDir()
        //}
        // 失败通知 TODO
        failure {
            echo '构建失败'
            wrap([$class: 'BuildUser']) {
                dingtalk (
                    robot: "${__REBOOT}",
                    type: 'ACTION_CARD',
                    title: "你有新的失败消息，请注意查收",
                    text: [
                        "# WEB项目名称-${APPLICATION_NAME}",
                        "-----------------------",
                        "* 任务: #${BUILD_NUMBER}  ",
                        "* 部署状态: 失败 ",
                        "* 执行人: ${BUILD_USER_ID}  ",
                        "* 执行人描述: ${BUILD_USER}  ",
                        "* 备注: 请查看jenkins构建日志  ",
                        "-----------------------"
                        
                    ],
                    btns: [
                        [
                            title: 'jenkins详情',
                            actionUrl: "${BUILD_URL}"
                        ]
                    ],
                    btnLayout: 'V'
                )
            }
            wrap([$class: 'BuildUser']) {
                dingtalk (
                    robot: "${__WEB_REBOOT}",
                    type: 'ACTION_CARD',
                    title: "你有新的失败消息，请注意查收",
                    text: [
                        "# WEB项目名称-${APPLICATION_NAME}",
                        "-----------------------",
                        "* 任务: #${BUILD_NUMBER}  ",
                        "* 部署状态: 失败 ",
                        "* 执行人: ${BUILD_USER_ID}  ",
                        "* 执行人描述: ${BUILD_USER}  ",
                        "* 备注: 请查看jenkins构建日志  ",
                        "-----------------------"
                        
                    ],
                    btns: [
                        [
                            title: 'jenkins详情',
                            actionUrl: "${BUILD_URL}"
                        ]
                    ],
                    btnLayout: 'V'
                )
            }  
        }
    }
}
}